<?php
/**
 *	description:ZMAXWECHAT token类实现文件
 *  author：min.zhang
 *  Email:zhang19min88@163.com
 *	Url:http://www.zmax99.com
 *  copyright:南宁市程序人软件科技有限责任公司保留所有权利
 *  date:2016-04-28
 *  @license GNU General Public License version 3, or later
 */
 
defined('_JEXEC') or die('Restricted access');

class zmaxwechatToken
{
	protected $appId ;
	protected $appSecret;
	protected $tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
	protected $token;
	
	
	public function __construct()
	{
		$params = JComponentHelper::getParams('com_zmaxwechat');
		$this->appId = $params->get("appId");
		$this->appSecret = $params->get("appSecret");
		$this->tokenUrl=$this->tokenUrl."&appid=".$this->appId."&&secret=".$this->appSecret;
		
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->select("*")->from("#__zmaxwechat_token");
		$db->setQuery($query);
		$this->token = $db->loadObject();
	}
	
	public function  getToken()
	{		
		//首先从数据库中拿
		if(!$this->token || !$this->isValidToken($this->token))
		{
			$this->refluseToken();//重写获得Token
		}
		return $this->token;
	}
	
	public function isValidToken($token)
	{
		if(!$token)	
		{
			return false;
		}
		if(!$token->token || !$token->time )
		{
			return false;
		}
		
		$curTime = new JDate();
		
		$tokenTime = new JDate($token->time);
		
		$expire = $token->expire;
		if($curTime->toUnix() - $tokenTime->toUnix() > $expire )
		{
			return false;
		}
		return true;
	}
	
	public function refluseToken()
	{	
		jimport('joomla.http.http');
		jimport('joomla.http.transport.curl');
		$options = new JRegistry();
		$transport =  new JHttpTransportCurl($options); 
		$http = new JHttp($options, $transport);
		$response = $http->get($this->tokenUrl);

		$result = json_decode($response->body);
		
		$newToken = new stdclass();
		$newToken->id=1 ;
		$newToken->token = $result->access_token;
		
		$curTime = new JDate();
		$newToken->time = $curTime->toSql();
		$newToken->expire = $result->expires_in;
		$newToken->guest=1;//待定
		$newToken->client_id=1;//待定
		
		$db = JFactory::getDBO();
		$db->updateObject("#__zmaxwechat_token",$newToken ,"id");
		
		$this->token = $newToken;
		
	}
	
}


